<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use EasyWeChat\Factory;
use EasyWeChat\Payment\Application;

class OrderPayRecord extends BaseModel
{
    public $errMsg;

    protected $table = "order_pay_records";

    public function order()
    {
        return $this->belongsTo('App\Model\Order','order_id','id');
    }

    public static function findByRefundId($refund_id)
    {
        return self::where('refund_id','=',$refund_id)->first();
    }

    public static function updateTradeState($order,$message)
    {
        $pr = self::where('order_id','=',$order->id)
            ->where('trade_state','=','NOTPAY')
            ->orderBy('created_at','desc')
            ->first();

        if($pr){
            if ( $message['result_code'] == 'SUCCESS') {
                $pr->trade_state = $message['result_code'];
                $pr->time_end = $message['time_end'];
                $pr->transaction_id = $message['transaction_id'];
            }
            $pr->save();
            return $pr;
        }
        return false;
    }

    public function refund($refund_desc = '退款')
    {
        $config = \Config::get('wechat.payment');
        //$payment = Factory::payment($config);
        //$payment = new Application(\Config::get('wechat'));

        $payment = app('wechat.payment');

        $model = $this;

        if ($model->trade_state != "SUCCESS" || !$model->transaction_id) {
            $this->errMsg = '未支付成功不能发起退款！';
            return false;
        }

        if (!env('WECHAT_PAYMENT_REFUND_NOTIFY_URL')) {
            $this->errMsg = '缺少配置参数不能发起退款！';
            return false;
        }

        if ($model->refund_id){
            $this->errMsg = '已发起过退款，请勿重复！';
            return false;
        }

        $model->out_refund_no = Helpers::createOrderRefundOutTradeNo();
        $model->refund_desc = $refund_desc;
        $model->refund_fee = $this->total_fee;
        $model->refund_notify_url = $config['default']['refund_notify_url'];
        $model->save();

        $fee = intval($model->refund_fee*100);

        $result = $payment->refund->byTransactionId($model->transaction_id,$model->out_refund_no,$fee,$fee,[
            'refund_desc' =>$model->refund_desc,
            'notify_url'=>$model->refund_notify_url,
        ]);

        Helpers::log('[refund] out_trade_no:'.$model->out_trade_no.' result:'.json_encode($result),'payment');

        if ($result) {

            if ($result['return_code'] == "SUCCESS"){
                $model->refund_result_code = $result['result_code'];
                if ($result['result_code'] == 'SUCCESS'){
                    $model->refund_id = $result['refund_id'];
                    $model->save();
                    return true;
                }else{
                    $model->save();
                    $this->errMsg = $result['err_code_des'];
                    return false;
                }
            }else{
                $this->errMsg = $result['return_msg'];
                return false;
            }
        }
        return false;
    }

    public static function paymentNotify($message)
    {
        $order = Order::findByOutTradeNo($message['out_trade_no']);

        if (!$order || $order->is_pay=="yes") {
            return true;
        }

        if ($message['return_code'] === 'SUCCESS') {
            // 用户支付成功
            if ($message['result_code'] === 'SUCCESS') {
                $order->pay_time = date('Y-m-d H:i:s');
                $order->is_pay = "yes";
                if ($order->state == 0) {
                    $order->state = 1;
                }

                $order->save(); // 保存订单
                OrderPayRecord::updateTradeState($order,$message);
            }
        }
        return false;
    }

    public static function refundNotify($message,$reqInfo)
    {
        if (!is_array($reqInfo)){
            $reqInfo = json_decode(json_encode($reqInfo),true);
        }

        $opr = OrderPayRecord::findByRefundId($reqInfo['refund_id']);

        if (!$opr || $opr->refund_status=="SUCCESS") {
            return true;
        }

        if (!is_array($reqInfo)){
            $reqInfo = json_decode(json_encode($reqInfo),true);
        }

        $opr->refund_success_fee = $reqInfo['refund_fee']*0.01;
        $opr->refund_status = $reqInfo['refund_status'];
        $opr->refund_account = $reqInfo['refund_account'];
        $opr->refund_recv_accout = $reqInfo['refund_recv_accout'];
        $opr->refund_success_time = $reqInfo['success_time'];
        $opr->save();

        $order = $opr->order;

        if ($order && $opr->refund_status == "SUCCESS"){
            $order->state = 10;
            $order->save();
        }
        return true;

    }
}
